<?php

namespace app\admin\command;

use app\admin\model\User;
use app\common\model\MoneyLog;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use \app\admin\model\share\ShareUser;
use \app\admin\model\share\Money as ShareMoney;
use \app\admin\model\share\Reward as ShareReward;
use \addons\shopro\model\Order;
use app\common\model\ShareConfig;
use app\common\model\Data;
use \app\admin\model\share\CommonShare;
use addons\shopro\model\User as ShopUser;
use think\Db;


class Profit extends Command
{
    protected function configure()
    {
        $this->setName('Profit')->setDescription("计划任务 Share");
    }

    protected function execute(Input $input, Output $output)
    {
        $output->writeln('Date Crontab job start...');
        /*** 这里写计划任务列表集 START ***/

        $order =  (new Order())->where(['is_share'=>0, 'status'=>1])->select();
        foreach ($order as $key => &$value) {
            (new CommonShare())->add_share_order($value->id,$value->goods_id,$value->user_id);
            //$this->order($value->id,$value->goods_id,$value->user_id); // $order_id, $goods_id, $user_id
        }
        /*** 这里写计划任务列表集 END ***/
        $output->writeln('Date Crontab job end...');
    }
    /**
     * 分销订单
     */
    public function order($order_id, $goods_id, $user_id)
    {
        if (empty($goods_id)) {
            return 0;
        }
        $shopro_order = (new Order())->where(['id'=>$order_id])->find();
        if (empty($shopro_order)) {
            return 0;
        }
        if ($shopro_order['status'] != 1) {
            return 0;
        }
        if ($shopro_order['user_id'] != $user_id) {
            return 0;
        }
        if ($shopro_order['is_share'] == 1) {
            return 0;
        }
        $user =(new ShareUser())->get(['user_id'=>$user_id]); // 分销用户
        if (empty($user)) { // 未添加 添加分销商
            return 0;
        }

        $ShareReward = ShareReward::where(['order_id'=>$order_id])->find();
        if (!empty($ShareReward)) {
            return 0;
        }

        $ShareConfig =  ShareConfig::where(['goods_id'=>$goods_id,'type'=>1])->find();

        if (empty($ShareConfig)) {
            $shopro_order->is_share = 1;
            $shopro_order->save();
            return 0;
        }
        $proportion = explode(",",$ShareConfig->reward);
        $this->add_reward(5,$proportion[0],$order_id);
        $this->add_reward(4,$proportion[1],$order_id);
        $this->add_reward(3,$proportion[2],$order_id);
        $this->add_reward(2,$proportion[3],$order_id);
        $this->add_reward(1,$proportion[4],$order_id);
        // 零售收益
        $parent_user =(new ShareUser())->get(['user_id'=>$user->inviter_id]); // 分销用户
        if (!empty($parent_user)) {
            $discount = $this->add_role($parent_user->role);
            $money = bcmul($discount, $shopro_order['pay_fee'],2);
            $this->add_money(1,$money,$order_id,$parent_user->user_id,$parent_user->role,$goods_id,1);
            // 批发收益
            $this->add_range($order_id,$parent_user->inviter_id,$parent_user->role,$shopro_order['pay_fee'],$goods_id);
        }

        // 未成为推广员 成为推广员
        if (!empty($user) && $user['role'] == 0) {
            $user->role = 1;
            $user->save();
        }
        // 上级及以上晋级
        (new ShareUser())->promotion_save($user->parent_id,$user->role,$user->role_type);
        $shopro_order->is_share = 2;
        $shopro_order->save();
        return 0;
    }

    // 上级用户晋级
    // private function add_promotion($user_id,$role,$role_type)
    // {
    //     $user =(new ShareUser())->get(['user_id'=>$user_id]); // 分销用户

    //     if (empty($user)) {
    //         return 0;
    //     }
    //      // 最高等级结束
    //      if ($user->role == 7) {
    //         return 0;
    //      }

    //      if ($role_type == 1) {
    //         $temp_role = $user->role1;
    //         if ($temp_role < $role) {
    //             $user->role1 = $role;
    //             $user->save();
    //         }
    //      }

    //      if ($role_type == 2) {
    //         $temp_role = $user->role2;
    //         if ($temp_role < $role) {
    //             $user->role2 = $role;
    //             $user->save();
    //         }
    //      }

    //      if ($role_type == 3) {
    //         $temp_role = $user->role3;
    //         if ($temp_role < $role) {
    //             $user->role3 = $role;
    //             $user->save();
    //         }
    //      }

    //     // 上级用户
    //     $temp_user =(new ShareUser())->get(['user_id'=>$user_id]); // 分销用户
    //     if ($temp_user->role >= 1 && $temp_user->role1 >= $temp_user->role && $temp_user->role2 >= $temp_user->role  && $temp_user->role3 >= $temp_user->role ) {
    //         $temp_user->role = bcadd($user->role,1);
    //         $temp_user->save();
    //     }
    //     return $this->add_promotion($user->parent_id,$temp_user->role,$user->role_type);
    // }


    private function add_reward($type,$money,$order_id)
    {
        $reward = new ShareReward();
        $reward->money = $money;
        $reward->type = $type;
        $reward->order_id = $order_id;
        $reward->addtime = time();
        $reward->mutual_money = bcmul(0.1, $money,2);
        $reward->save();
    }

    // type 1 直推 2极差 3日创收 4周创收
    private function add_money($type,$money,$order_id,$user_id,$role,$goods_id,$is_one=0)
    {
        if (!empty($money) && $money !="0.00") {
//            $money = round($money);
//            if($money != 0){
                $ShareMoney = new ShareMoney();
                $ShareMoney->money = $money;
                $ShareMoney->mutual_money = bcmul(0.1, $money,2);
                $ShareMoney->type = $type;
                $ShareMoney->order_id = $order_id;
                $ShareMoney->user_id = $user_id;
                $ShareMoney->goods_id = $goods_id;
                $ShareMoney->role = $role;
                $ShareMoney->addtime = time();
                if($type == 1 || $type == 2){
                    $ShareMoney->is_grant = 0;
                }
                $ShareMoney->save();
                /*qi11.9
                 * $user =(new ShareUser())->get(['user_id'=>$user_id]); // 分销用户
                $old_mutual_money = $user->mutual_money;

                //获取不通等级分给佣金的比例 qi11.3
                $con_ddata = Db::name("share_config")->where(['role'=>$role,'type'=>3])->find();
                //$user->price += bcmul(0.9, $money, 2);
                $price_bl = 1-$con_ddata['reward'];
                $mutual_money_bl = $con_ddata['reward'];

                $user->price += bcmul($price_bl, $money,2);
                $user->total_price += $money;
                $user->mutual_money += bcmul($mutual_money_bl, $money,2);
                $user->save();
                ShopUser::mutual(bcmul($mutual_money_bl, $money,2), $user_id, 'mutual_add', $order_id, '',[],$old_mutual_money);
                $after = bcmul($price_bl, $money,2) + $user->price;
                if($is_one == 1){
                    $memo = '零售收益';
                    $cz_type = 10;
                }elseif ($is_one == 2){
                    $memo = '批发收益';
                    $cz_type = 11;
                }
                MoneyLog::create(['user_id' => $user_id, 'money' => bcmul($price_bl, $money,2), 'before' => $user->price, 'after' => $after, 'type' => $cz_type, 'memo' => $memo, 'order_id'=>$order_id,'mutual_money'=>bcmul($mutual_money_bl, $money,2)]);*/

                //            }
        }
    }

    // 奖励级别 // "1":'推广员',"2":'代言人',"3":'一星网店经销商',"4":'二星网店经销商',"5":'银牌经销商',"6":'金牌经销商',"7":'钻石经销商'
    private function add_role($role)
    {
        $ShareConfig =  ShareConfig::where(['goods_id'=>0,'type'=>0,'role'=>$role])->find();
        if (empty($ShareConfig)) {
            $discount = 0;
        } else {
            $discount = $ShareConfig->proportion;
        }

        return $discount;
    }

    /**
     * order_id 订单id
     * user_id 用户id
     * role 上一级等级
     * pay_fee 支付金额
     */
    private function add_range($order_id,$user_id,$role,$pay_fee,$goods_id)
    {
        $user =(new ShareUser())->get(['user_id'=>$user_id]); // 分销用户
        if (empty($user)) {
            return 0;
        }
        // 最高等级结束
        if ($user->role == 7) {
            if ($user->role == $role) {
                return 0;
            } else {
                $discount1 = $this->add_role($role);
                $discount2 = $this->add_role($user->role);
                $discount = bcsub($discount2,$discount1,2);
                if ($discount <= 0) {
                    return 0;
                }
                $money = bcmul($discount, $pay_fee,2);
                $this->add_money(2,$money,$order_id,$user->user_id,$user->role,$goods_id,2);
                return 0;
            }

        }
        // 同级下级不奖励
        if ($user->role <= $role) {
            return $this->add_range($order_id,$user->inviter_id,$role,$pay_fee,$goods_id);
        } else {
            $discount1 = $this->add_role($role);
            $discount2 = $this->add_role($user->role);
            $discount = bcsub($discount2,$discount1,2);
            $money = bcmul($discount, $pay_fee,2);
            $this->add_money(2,$money,$order_id,$user->user_id,$user->role,$goods_id,2);
            return $this->add_range($order_id,$user->inviter_id,$user->role,$pay_fee,$goods_id);
        }
    }

    // // 上级用户晋级
    // private function add_promotion($user_id)
    // {
    //     $user =(new ShareUser())->get(['user_id'=>$user_id]); // 分销用户
    //     if (empty($user)) {
    //         return 0;
    //     }
    //      // 最高等级结束
    //      if ($user->role == 7) {
    //         return 0;
    //      }

    //      switch ($user->role) {
    //         case 1:
    //             $this->promotion($user_id,1);
    //             break;
    //         case 2:
    //             $this->promotion($user_id,2);
    //             break;
    //         case 3:
    //             $this->promotion($user_id,3);
    //             break;
    //         case 4:
    //             $this->promotion($user_id,4);
    //             break;
    //         case 5:
    //             $this->promotion($user_id,5);
    //             break;
    //         case 6:
    //             $this->promotion($user_id,6);
    //             break;
    //         default:
    //             break;
    //     }
    //     $this->add_promotion($user->parent_id);
    // }

    private function promotion($user_id,$role)
    {
        $parent_user =(new ShareUser())->where(['parent_id'=>$user_id])->select();
        if (count($parent_user) < 3) {
            return 0; // 本身 a
        } else {
            $temp_num = 0;
            foreach ($parent_user as $value) {
                $shareAll = (new ShareUser())->where(['is_delete'=>0])->select();
                # 获取所有的下级成员
                $sonShareAll = Data::channelList($shareAll, $value['user_id'], "", 'user_id', 'parent_id');
                if ($value['role'] == $role) {
                    $temp_num += 1;
                    continue;;
                }
                foreach ($sonShareAll as  $user1) {
                    if ($user1['role'] == $role) {
                        $temp_num += 1;
                        break;
                    }
                }
            }
            if ($temp_num == 3) {
                $user =(new ShareUser())->get(['user_id'=>$user_id]); // 分销用户
                $user->role = bcadd($user->role,1);
                $user->save();
            }
            return  0;
        }
    }
}
